package com.mvu.banana.common.server;

import com.mvu.banana.common.client.ServiceToken;
import com.mvu.banana.common.client.SystemConstants;
import com.mvu.banana.domain.finder.CredentialFinder;
import com.mvu.banana.domain.stub.Credential;
import org.apache.log4j.Logger;
import org.jasypt.util.password.BasicPasswordEncryptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: mvu
 * Date: 5/27/11
 * Time: 6:20 PM
 * To change this template use File | Settings | File Templates.
 */
public class SessionManager implements SystemConstants, ISessionManager {
  static final Logger logger = Logger.getLogger(SessionManager.class);
  static ISessionManager INSTANCE;

  private SessionManager() {
  }

  public static ISessionManager get() {
    if (INSTANCE == null) {
      INSTANCE = new SessionManager();
    }
    return INSTANCE;
  }

  private static final String SERVICE_TOKEN = "SESSION_TOKEN";

  public ServiceToken login(HttpServletRequest request) {
    ServiceToken token = getServiceToken(request);
    int logInCount = token.getLogInCount();
    Date lastLogIn = token.getLastLogIn();
    Date now = new Date();
    if (logInCount > 2) {
      if (now.getTime() - lastLogIn.getTime() < 600000) {
        request.setAttribute(SYSTEM_MESSAGE, TOO_MANY_ATTEMPT);
        return token;
      }
    }
    String email = request.getParameter(EMAIL_ATTR);
    if (email == null) {
      email = (String) request.getAttribute(EMAIL_ATTR);
    }
    String password = request.getParameter(PASSWORD_ATTR);
    if (password == null) {
      password = (String) request.getAttribute(PASSWORD_ATTR);
    }
    Credential credential = CredentialFinder.find(email);
    BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
    if (credential != null && passwordEncryptor.checkPassword(password, credential.getPassword())) {
      token.setUsername(credential.getUsername());
      token.setLogInCount(0);
      token.setLastLogIn(null);
      return token;
    }
    logger.info("Login fail: email=" + email + ", credential=" + credential);
    token.setLastLogIn(now);
    token.setLogInCount(logInCount + 1);
    request.setAttribute(SYSTEM_MESSAGE, INVALID_CREDENTIAL);
    return token;
  }

  public void logout(HttpServletRequest request) {
    HttpSession _entityManager = request.getSession(false);
    _entityManager.invalidate();
  }

  public ServiceToken getServiceToken(HttpServletRequest request) {
    HttpSession _entityManager = request.getSession(true);
    ServiceToken token = (ServiceToken) _entityManager.getAttribute(SERVICE_TOKEN);
    if (token == null) {
      token = new ServiceToken();
      _entityManager.setAttribute(SERVICE_TOKEN, token);
    }
    return token;
  }
}